package com.rc.common.config.reids;

import org.springframework.core.convert.ConversionService;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;

/**
 * 自定义Redis缓存实现
 * 扩展了RedisCache的功能，支持通配符删除
 */
public class CustomizedRedisCache extends RedisCache {
    // 通配符
    private static final String WILD_CARD = "*";
    // 缓存名称
    private final String name;
    // Redis缓存写入器
    private final RedisCacheWriter cacheWriter;
    // 类型转换服务
    private final ConversionService conversionService;

    /**
     * 构造函数
     * @param name 缓存名称
     * @param cacheWriter Redis缓存写入器
     * @param cacheConfig Redis缓存配置
     */
    protected CustomizedRedisCache(String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig) {
        super(name, cacheWriter, cacheConfig);
        this.name = name;
        this.cacheWriter = cacheWriter;
        this.conversionService = cacheConfig.getConversionService();
    }

    /**
     * 删除缓存
     * @param key 缓存键，支持通配符
     */
    @Override
    public void evict(Object key) {
        // 如果key是字符串且包含通配符
        if (key instanceof String keyString && keyString.contains(WILD_CARD)) {
            // 创建缓存键
            String cacheKey = this.createCacheKey(keyString);
            // 将键转换为字节数组
            byte[] pattern = conversionService.convert(cacheKey, byte[].class);
            // 清理匹配模式的缓存
            this.cacheWriter.clean(this.name, pattern);
            return;
        }
        // 否则调用父类方法
        super.evict(key);
    }
}